package com.wltt.product.frfront.utils;

import com.wltt.product.frfront.model.HttpResult;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public abstract class ResponseUtil {

    /**
     * 返回
     *
     * @param response
     * @return
     */
    public static void writeResponse(HttpServletResponse response, HttpResult httpResult) throws IOException {
        writeResponse(response, httpResult.getHttpCode(), httpResult.getHeaders(), httpResult.getBody());
    }

    /**
     * 返回
     *
     * @param response
     * @return
     */
    public static void writeResponse(HttpServletResponse response, HttpStatus httpStatus, Object body) throws IOException {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=UTF-8");
        writeResponse(response, httpStatus.value(), headers, JsonUtil.toJson(body));
    }

    /**
     * 返回
     *
     * @param response
     * @return
     */
    private static void writeResponse(HttpServletResponse response, int httpStatus, Map<String, String> headers, String body) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setStatus(httpStatus);
        if (null != headers && headers.size() > 0) {
            headers.forEach((k, v) -> response.setHeader(k, v));
        }

        try (PrintWriter writer = response.getWriter()) {
            writer.write(body);
            writer.flush();
        }
    }
}
